package net.maku.module.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import net.maku.framework.common.utils.Result;
import net.maku.framework.operatelog.annotations.OperateLog;
import net.maku.framework.operatelog.enums.OperateTypeEnum;
import net.maku.framework.security.user.SecurityUser;
import net.maku.module.query.AgThirdPartyQuery;
import net.maku.module.service.AgThirdPartyService;
import net.maku.module.entity.AgThirdParty;
import net.maku.module.util.UrlReplaceUtil;
import net.maku.storage.service.StorageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 三方平台地址管理(AgThirdParty)表控制层
 *
 * @author ChiHongYu
 * @since 2025-01-09 10:06:46
 */
@Tag(name = "三方平台地址管理接口")
@RestController
@RequestMapping("agThirdParty")
public class AgThirdPartyController {

    @Resource
    private AgThirdPartyService agThirdPartyService;
    @Resource
    private StorageService storageService;

    @Autowired
    private UrlReplaceUtil urlReplaceUtil;


    @Operation(summary = "创建/修改")
    @PostMapping("createOrUpdate")
    public Result<AgThirdParty> create(@RequestBody AgThirdPartyQuery param) {
        if (SecurityUser.getUser() == null)
            return Result.error(403, "未登录，权限认证失败");
        long executor = SecurityUser.getUser().getId();
        return agThirdPartyService.createOrUpdate(param, executor);
    }


    @Operation(summary = "查询详情")
    @GetMapping("get")
    public Result<AgThirdParty> get(@RequestParam("id") Integer id) {
        AgThirdParty agThirdParty = this.agThirdPartyService.queryById(id);
        return Result.ok(agThirdParty);
    }


    @Operation(summary = "获取列表")
    @GetMapping("getList")
    public Result<List<AgThirdParty>> getList(HttpServletRequest request,@RequestParam int websiteId) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("websiteId", websiteId);
        List<AgThirdParty> list = agThirdPartyService.getList(param);
        urlReplaceUtil.thirdParty(request,list);
        return Result.ok(list);
    }


    @Operation(summary = "删除")
    @GetMapping("del")
    public Result del(@RequestParam int id) {
        boolean opResult = this.agThirdPartyService.deleteById(id);
        if (opResult) {
            return Result.ok();
        } else {
            return Result.error(500, "服务器错误，请联系管理员");
        }
    }

    @PostMapping("/upload")
    @Operation(summary = "上传图片")
    @OperateLog(type = OperateTypeEnum.INSERT)
    public Result<Object> upload(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> response = new HashMap<>();
        if (file.isEmpty()) {
            return Result.error(400, "请选择需要上传的文件");
        }
        String contentType = file.getContentType();
        String fileTypeCategory = null;
        if (contentType != null) {
            fileTypeCategory = getFileTypeCategory(contentType);
        }
        if (StringUtils.isBlank(fileTypeCategory)) {
            return Result.error("不支持的文件类型");
        }
        try {
            // 上传路径
            String path = storageService.getPath(file.getOriginalFilename());
            // 上传文件
            String url = storageService.upload(file.getBytes(), path);
            // 成功返回
            Map<String, Object> data = new HashMap<>();
            data.put("url", url); // 必须
            data.put("alt", file.getOriginalFilename()); // 非必须
            data.put("href", url); // 非必须
            return Result.ok(data);
        } catch (Exception e) {
            Result.error(500, e.getMessage());
        }
        return Result.error();
    }

    private String getFileTypeCategory(String contentType) {
        if (contentType.startsWith("image")) {
            return "image";
        }
        return null;
    }

}
